package com.lw.common.base

import android.app.Application
import android.content.ContextWrapper
import android.util.Log
import android.widget.TextView
import androidx.multidex.MultiDexApplication
import com.drake.statelayout.StateConfig
import com.hjq.toast.Toaster
import com.kongzue.dialogx.DialogX
import com.lw.common.customview.FadeStateChangedHandler
import com.lw.common.exception.ErrorCode
import com.lw.common.exception.HandleException
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.mmkv.MMKV


/**
 * Base Application
 */
class BaseApplication : MultiDexApplication() {
    companion object {
        private const val TAG = "App"
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        DialogX.init(this)
        DialogX.onlyOnePopTip = true

//        Toast初始化
        Toaster.init(this)
//        本地储存初始化
        MMKV.initialize(this)
        initGlobalHandleException()

        //全局设置默认的 Header
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            //开始设置全局的基本参数（这里设置的属性只跟下面的MaterialHeader绑定，其他Header不会生效，能覆盖DefaultRefreshInitializer的属性和Xml设置的属性）
            layout.setEnableHeaderTranslationContent(false)
            MyRefreshHeader(context)
        }
        initStateView()
    }

    /**
     * 初始化StateView
     */
    private fun initStateView() {
        StateConfig.apply {
            emptyLayout = com.lw.common.R.layout.layout_empty
            errorLayout = com.lw.common.R.layout.layout_error
            loadingLayout = com.lw.common.R.layout.layout_loading
            onError {
                findViewById<TextView>(com.lw.common.R.id.layout_error_content).text = (it ?: "请检查网络，稍后重试").toString()
            }
            stateChangedHandler = FadeStateChangedHandler()
        }
    }

    /**
     * 全局异常处理
     */
    private fun initGlobalHandleException() {
        HandleException.setListener { e ->
            Log.e(TAG, "全局异常：" + e.msg)
            if (e.code == ErrorCode.TOKEN_ERROR.code) {

            }
        }
    }
}

private lateinit var instance: Application

object AppContext : ContextWrapper(instance)


